package cn.etg.product2503.controller;

import cn.etg.product2503.common.Result;
import cn.etg.product2503.entity.PageBean;
import cn.etg.product2503.entity.Product;
import cn.etg.product2503.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/products")
public class ProductController {
    @Autowired
    private ProductService productService;
    @PostMapping()
    public Result<Product> createProduct(@RequestBody Product product) {
        Product product1 = productService.selectbyname(product.getName());
        if (product1!= null) {
            return Result.error(400, "商品名称已存在");
        }
         productService.createProduct(product);
        Product newProduct = productService.selectbyname(product.getName());
         return Result.success("添加成功", newProduct);

    }

    //products/{id}
    @DeleteMapping("/{id}")
    public Result deleteProduct(@PathVariable("id") Long id) {
        productService.deleteProduct(id);
        return Result.success("删除成功");
    }

    @PutMapping("/{id}")
    public Result<Product> updateProduct(@PathVariable("id") Long id, @RequestBody Product product) {
        Product product1 = productService.selectbyname(product.getName());
        if (product1!= null&&!product1.getId().equals(id)) {
            return Result.error(400, "商品名称已存在");
        }
        productService.updateProduct(id, product);
        Product newProduct = productService.selectbyname(product.getName());
        return Result.success("更新成功", newProduct);
    }
    @GetMapping
    public Result<PageBean<Product>> queryArticle(Integer pageNum,
                                                  Integer pageSize,
                                                  @RequestParam(required = false)  String keyword){
        PageBean<Product> pageBean = productService.queryProduct(pageNum, pageSize, keyword);
        pageBean.setPageNum(pageNum);
        pageBean.setPageSize(pageSize);
        return Result.success("查询成功", pageBean);
    }


}
